package main

import (
	"backend/config"
	"context"
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type App struct {
	Config  *config.Configuration
	logger  *zap.Logger
	httpSrv *http.Server
}

func newHTTPServer(cfg *config.Configuration, router *gin.Engine) *http.Server {
	return &http.Server{
		Addr:    ":" + cfg.App.Port,
		Handler: router,
	}
}

func newApp(cfg *config.Configuration, logger *zap.Logger, httpSrv *http.Server) *App {
	return &App{
		Config:  cfg,
		logger:  logger,
		httpSrv: httpSrv,
	}
}

func (a *App) Run() error {
	// 添加详细日志输出
	a.logger.Info("准备启动HTTP服务器", zap.String("addr", a.httpSrv.Addr))
	fmt.Printf("HTTP服务器即将启动在端口: %s\n", a.httpSrv.Addr)

	// 启动 http server
	go func() {
		fmt.Println("HTTP服务器启动中...")
		a.logger.Info("http server started", zap.String("addr", a.httpSrv.Addr))
		fmt.Printf("HTTP服务器已启动在: %s\n", a.httpSrv.Addr)
		if err := a.httpSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			a.logger.Error("HTTP服务器启动失败", zap.Error(err))
			fmt.Printf("HTTP服务器启动失败: %v\n", err)
			panic(err)
		}
	}()

	// 确保服务器有时间启动
	time.Sleep(500 * time.Millisecond)
	fmt.Println("应用启动完成")
	return nil
}
func (a *App) Stop(ctx context.Context) error {
	// 关闭 http server
	a.logger.Info("http server has been stop")
	if err := a.httpSrv.Shutdown(ctx); err != nil {
		return err
	}

	// 关闭 queue consumer
	//a.logger.Info("queue consumer has been stop")
	//if err := a.consumerSrv.Stop(ctx); err != nil {
	//   return err
	//}

	return nil
}
